package guda.house.web.action.bill;

import guda.grape.autogen.common.page.BizResult;
import guda.grape.util.RequestUtil;
import guda.house.biz.AccountEstateBiz;
import guda.house.biz.beans.vo.AccountEstateXlsVO;
import guda.house.biz.beans.vo.JsonResult;
import guda.house.biz.form.bill.AccountEstateEditForm;
import guda.house.biz.form.bill.AccountEstateForm;
import guda.house.biz.form.bill.AccountEstateSearchForm;
import guda.house.biz.query.AccountEstateQuery;
import guda.house.biz.security.AppUtil;
import guda.house.biz.util.DateUtil;
import guda.house.biz.util.ErrorCode;
import guda.house.biz.util.ExportExcelUtil;
import guda.house.biz.util.PriceUtil;
import guda.house.dal.dao.VillageDAO;
import guda.house.dal.dataobject.AccountEstateDO;
import guda.house.dal.dataobject.VillageDO;
import guda.house.web.helper.ResponseHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by well on 15/11/16.
 */
@Controller
@RequestMapping(value = "bill/accountEstate")
public class AccountEstateAction {

    @Autowired
    private AccountEstateBiz accountEstateBiz;
    @Autowired
    private VillageDAO villageDAO;

    @RequestMapping(value = "list.htm", method = RequestMethod.GET)
    public String list(HttpServletRequest request, ModelMap modelMap,AccountEstateSearchForm accountEstateSearchForm) {
        int pageId = RequestUtil.getInt(request, "pageNo");
        int pageSize = RequestUtil.getInt(request, "pageSize");
        if(accountEstateSearchForm.getVillageId() == null) {
            List<Long> villageIdList = AppUtil.getVillageIdList();
            if (villageIdList.size() > 0) {
                accountEstateSearchForm.setVillageId(villageIdList.get(0));
            }
        }
        AccountEstateQuery accountEstateQuery = new AccountEstateQuery();
        accountEstateQuery.setPageNo(pageId);
        accountEstateQuery.setPageSize(pageSize);
        accountEstateQuery.setVillageId(accountEstateSearchForm.getVillageId());
        if(accountEstateSearchForm.getStartDate()!=null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            try {
                accountEstateQuery.setStartDate(simpleDateFormat.parse(accountEstateSearchForm.getStartDate()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if(accountEstateSearchForm.getEndDate()!=null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            try {
                accountEstateQuery.setEndDate(simpleDateFormat.parse(accountEstateSearchForm.getEndDate()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        modelMap.put("query", accountEstateQuery);
        BizResult bizResult = accountEstateBiz.list(accountEstateQuery);
        if (bizResult.success) {
            modelMap.putAll(bizResult.data);
            return "bill/accountEstate/list.vm";
        } else {
            return "redirect:/error.htm?code=" + bizResult.code;
        }
    }

    @RequestMapping(value = "edit.htm", method = RequestMethod.GET)
    public String edit(HttpServletRequest request, ModelMap modelMap, AccountEstateEditForm accountEstateEditForm,
                       BindingResult result, Map<String, Object> model) {
        long id = RequestUtil.getLong(request, "id");
        BizResult bizResult = accountEstateBiz.detail(id);
        if (bizResult.success) {
            modelMap.putAll(bizResult.data);
            accountEstateEditForm.initForm(((AccountEstateDO) bizResult.data.get("accountEstateDO")));
            return "bill/accountEstate/edit.vm";
        } else {
            return "redirect:/error.htm?code=" + bizResult.code;
        }

    }


    @RequestMapping(value = "/create.htm", method = RequestMethod.GET)
    public String create(HttpServletRequest request, ModelMap modelMap, AccountEstateForm accountEstateForm,
                         BindingResult result) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(new Date());
        accountEstateForm.setGmtAccount(format);
        return "bill/accountEstate/create.vm";
    }

    @RequestMapping(value = "/doCreate.htm", method = RequestMethod.POST)
    public String doCreate(HttpServletRequest request, ModelMap modelMap, @Valid AccountEstateForm accountEstateForm,
                           BindingResult result) {
        if (result.hasErrors()) {
            return "bill/accountEstate/create.vm";
        }
        AccountEstateDO accountEstateDO = accountEstateForm.toDO();
        BizResult bizResult = accountEstateBiz.create(accountEstateDO);
        if (bizResult.success) {
            return "redirect:/bill/accountEstate/list.htm";
        } else {
            return "redirect:/error.htm?code=" + bizResult.code;
        }

    }

    @RequestMapping(value = "/doUpdate.htm", method = RequestMethod.POST)
    public String doUpdate(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap, @Valid AccountEstateEditForm accountEstateEditForm,
                           BindingResult result, Map<String, Object> model) {
        if (result.hasErrors()) {
            return "bill/accountEstate/edit.vm";
        }
        AccountEstateDO accountEstateDO = accountEstateEditForm.toDO();
        BizResult bizResult = accountEstateBiz.update(accountEstateDO);
        if (bizResult.success) {
            return "redirect:/bill/accountEstate/list.htm";
        } else {
            return "redirect:/error.htm?code=" + bizResult.code;
        }

    }

    @RequestMapping(value = "/doDelete.htm")
    public void doDelete(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        long id = RequestUtil.getLong(request, "id");
        BizResult bizResult = accountEstateBiz.delete(id);
        JsonResult result = JsonResult.getInstance();
        if (bizResult.success) {
            ResponseHelper.ajaxReturn(result.getMap(), response);
            return;
        } else {
            result.setErrMsg(ErrorCode.getMessage(bizResult.code));
            ResponseHelper.ajaxReturn(result.getMap(), response);
            return;
        }

    }


    @RequestMapping(value = "export.do", method = RequestMethod.GET)
    public void export(HttpServletResponse response, ModelMap modelMap,AccountEstateSearchForm accountEstateSearchForm) {
        AccountEstateQuery accountEstateQuery = new AccountEstateQuery();
        accountEstateQuery.setPageSize(10000);
        accountEstateQuery.setVillageId(accountEstateSearchForm.getVillageId());
        if(accountEstateSearchForm.getStartDate()!=null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            try {
                accountEstateQuery.setStartDate(simpleDateFormat.parse(accountEstateSearchForm.getStartDate()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if(accountEstateSearchForm.getEndDate()!=null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            try {
                accountEstateQuery.setEndDate(simpleDateFormat.parse(accountEstateSearchForm.getEndDate()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        BizResult bizResult = accountEstateBiz.list(accountEstateQuery);
        List<AccountEstateDO> accountEstateDOList = (List<AccountEstateDO>)bizResult.data.get("accountEstateList");
        List<AccountEstateXlsVO> accountEstateXlsVOList = new ArrayList<AccountEstateXlsVO>(accountEstateDOList.size());
        for(AccountEstateDO accountEstateDO:accountEstateDOList){
            AccountEstateXlsVO accountEstateXlsVO = new AccountEstateXlsVO();
            VillageDO villageById = villageDAO.getVillageById(accountEstateDO.getVillageId());
            accountEstateXlsVO.setVillageName(villageById.getVillageName());
            accountEstateXlsVO.setAccountComment(accountEstateDO.getAccountComment());
            accountEstateXlsVO.setAccountMoney(PriceUtil.formatCNY(accountEstateDO.getAccountMoney()));
            accountEstateXlsVO.setAccountType(accountEstateDO.getAccountType());
            accountEstateXlsVO.setGmtAccount(DateUtil.formatYMD(accountEstateDO.getGmtAccount()));
            accountEstateXlsVOList.add(accountEstateXlsVO);
        }
        String filedisplay = null;
        try {
            filedisplay = URLEncoder.encode("物业支出.xls", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setContentType("application/x-download; charset=UTF-8");
        response.addHeader("Content-Disposition", "attachment; filename=" + filedisplay);
        String[] headers = new String[]{"小区","支出金额","支出时间","支出类型","备注"};
        String[] fields = new String[]{"villageName","accountMoney","gmtAccount","accountType","accountComment"};
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            ExportExcelUtil.exportExcel("物业支出", headers, fields, accountEstateXlsVOList, outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
